//
//  SEGQinlinBluetoothDoorManager.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/7/10.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGQinlinBluetoothDoorManager.h"
#import "SEGIBluetooth.h"

static NSTimeInterval const kTimeInterval = 10.f;

@interface SEGQinlinBluetoothDoorManager () <CBPeripheralManagerDelegate, SEGIBluetoothDelegate>

@property (nonatomic, strong) SEGIBluetooth* bluetooth; //亲邻科技蓝牙
@property (nonatomic, copy) dispatch_block_t doorHandleCallback; //超时取消开门

@end

@implementation SEGQinlinBluetoothDoorManager

- (instancetype)init {
    self = [super init];
    if (self) {
        self.bluetooth = [SEGIBluetooth sharedManager];
    }
    return self;
}

- (void)openDoor
{    
    // 延迟10秒强制取消
    WeakSelf;
    self.doorHandleCallback = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
        [weakSelf seg_timeOutAction];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTimeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), self.doorHandleCallback);
    
    self.bluetooth.deviceName = self.doorModel.ssid;
    self.bluetooth.delegate = self;
    [self.bluetooth setUp];
}

#pragma mark - 亲临科技蓝牙
- (void)didWriteData
{
    [self seg_afterOpenDoorSuccess];
}
#pragma mark - 私有方法
- (void)seg_afterOpenDoorSuccess
{
    SEGLog(@"seg_afterOpenDoorSuccess");
    [self seg_deallocValues];
//    if (self.delegate && [self.delegate respondsToSelector:@selector(managerOpenDoorSuccessWithShouldShowTips:)]) {
//        [self.delegate managerOpenDoorSuccessWithShouldShowTips:YES];
//    }
    if (self.delegateSubject) {
        [self.delegateSubject sendNext:nil];
        [self.delegateSubject sendCompleted];
    }
    // 拿到确定的结果 就停止延迟回调的block
    if (self.doorHandleCallback) {
        dispatch_block_cancel(self.doorHandleCallback);
        self.doorHandleCallback = nil;
    }
}

- (void)seg_timeOutAction
{
    SEGLog(@"seg_timeOutAction");
    [self seg_deallocValues];
//    if (self.delegate && [self.delegate respondsToSelector:@selector(managerOpenDoorFailedWithMessage:)]) {
//        [self.delegate managerOpenDoorFailedWithMessage:kOpenDoorMessage_Failed];
//    }
    if (self.delegateSubject) {
        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:SEGOpenDoorErrorType_OpenBluetoothDoorFail userInfo:@{NSLocalizedDescriptionKey:kOpenDoorMessage_Failed}];
        [self.delegateSubject sendError:error];
    }
}

//销毁变量
- (void)seg_deallocValues
{
    SEGLog(@"seg_deallocValues");
    self.bluetooth.delegate = nil;
    // 取消延迟
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark - CBPeripheralManagerDelegate
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager*)peripheral
{
    switch (peripheral.state) {
            //蓝牙开启且可用
        case CBPeripheralManagerStatePoweredOn:
        {
            SEGLog(@"now we are searching device...\n");
            break;
        }
        default:
            break;
    }
}

@end
